package com.source.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.lang.StringEscapeUtils;

public class DbUtil {

	// get connection to DB
	protected static Connection getConn() {
		Connection conn = null;
		String url = "jdbc:mysql://ec2-54-201-181-147.us-west-2.compute.amazonaws.com:3306/";
		String db = "test";
		String driver = "com.mysql.jdbc.Driver";
		String user = "ec2-sql";
		String pass = "sCrumm3r";
		try {
			Class.forName(driver).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(url + db, user, pass);
		} catch (SQLException e) {
			System.err.println("Mysql Connection Error: ");
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * escape string to db
	 * 
	 * remove harmfull db content remove harmfull tags
	 * 
	 * @param s
	 * @return
	 */
	protected static String escapeForSql(String s) {
		// remove harmful HTML tags
		if (s != null) {
			s = s.replaceAll("(?i)</?(HTML|SCRIPT|HEAD|CSS)\\b[^>]*>", "");
		}
		String rtn = StringEscapeUtils.escapeSql(s);
		// escape utils returns null if null
		if (rtn == null) {
			rtn = "";
		}
		return rtn;
	}

}